package jch.learn.java.advanced.chapter4_network;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Scanner;

public class TestSocketTimeout {

    public static void main(String[] args) {
        Socket s = null;
        try {
            s = new Socket("www.google.com", 80);
        } catch (IOException e) {
            System.out.println("Socket 链接异常！");
            e.printStackTrace();
        }

        if (s != null) {
            try {
                s.setSoTimeout(10000);
                Scanner in = new Scanner(s.getInputStream());
                Writer writer = new OutputStreamWriter(s.getOutputStream());
                writer.write("张三");
                writer.flush();
                s.shutdownOutput();
                while (in.hasNextLine()) {
                    String line = in.nextLine();
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.out.println(e instanceof SocketTimeoutException);
                e.printStackTrace();
                System.out.println("Socket 读取超时！");
            }
        }

        test();
    }

    private static void test(){
        Socket s = new Socket();
        try {
            s.connect(new InetSocketAddress("www.google.com",80),1000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
